package com.lagou.demo;

import com.lagou.mapper.UserMapper;
import com.lagou.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisRedisTest {

    private UserMapper userMapper1;
    private UserMapper userMapper2;
    private UserMapper userMapper3;
    private SqlSession sqlSession1;
    private SqlSession sqlSession2;
    private SqlSession sqlSession3;

    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        sqlSession1 = sqlSessionFactory.openSession(true);
        sqlSession2 = sqlSessionFactory.openSession(true);
        sqlSession3 = sqlSessionFactory.openSession(true);
        userMapper1 = sqlSession1.getMapper(UserMapper.class);
        userMapper2 = sqlSession2.getMapper(UserMapper.class);
        userMapper3 = sqlSession3.getMapper(UserMapper.class);
    }

    @After
    public void after() {
        if (sqlSession1 != null) sqlSession1.close();
        if (sqlSession2 != null) sqlSession2.close();
        if (sqlSession3 != null) sqlSession3.close();
    }

    @Test
    public void SecondLevelCache() throws IOException {
        User user = userMapper1.findById(1);
        System.out.println(user);
        sqlSession1.close(); //清空⼀级缓存
        user.setUsername("redis");
        userMapper3.update(user);
        sqlSession3.commit();
        User user2 = userMapper2.findById(1);
        System.out.println(user2);
    }
}
